<template>
  <el-dialog
    width="400px"
    :title="showTitle"
    destroy-on-close
    type="primary"
    :visible="showDialog"
    @close="handleClose"
  >
    <el-form ref="addForm" :rules="addRules" :model="addForm">
      <el-form-item
        v-if="!id"
        label="所属学科"
        size="small"
        label-width="80px"
        prop="subjectID"
      >
        <el-select
          placeholder="请选择"
          style="width: 100%"
          v-model="addForm.subjectID"
        >
          <el-option
            v-for="item in simpleList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="目录名称"
        size="small"
        label-width="80px"
        prop="directoryName"
      >
        <el-input
          v-model="addForm.directoryName"
          type="text"
          placeholder="请输入目录名称"
          style="width: 100%"
        ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer" style="text-align: right">
      <div>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="dialogSubmit">确认</el-button>
      </div>
    </span>
  </el-dialog>
</template>

<script>
import { update, add } from '@/api/hmmm/directorys'

export default {
  name: 'css',
  data () {
    return {
      addRules: {
        subjectID: [
          { required: true, message: '请选择所属学科', trigger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ]
      }
    }
  },

  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    simpleList: {
      type: Array,
      required: true
    },
    addForm: {
      type: Object,
      required: true
    },
    id: {}
  },
  computed: {
    showTitle () {
      return this.addForm.id ? '编辑目录' : '新增目录'
    }
  },
  created () {
    // console.log(this.id)
  },
  methods: {
    handleClose () {
      this.$emit('update:showDialog', false)
      this.$refs.addForm.resetFields()
      this.$emit('clearAddForm')
    },
    dialogSubmit () {
      if (this.id) {
        this.addForm.subjectID = Number(this.id)
      }
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return
        if (this.addForm.id) {
          await update(this.addForm)
          this.$message.success('修改目录成功')
          // 关闭弹窗
          this.handleClose()
          // 重新获取列表
          this.$emit('getList')
        } else {
          await add(this.addForm)
          this.$message.success('添加目录成功')
          // 关闭弹窗
          this.handleClose()
          // 重新获取列表
          this.$emit('getList')
        }
      })
    }
  }
}
</script>

<style scoped lang="less"></style>
